package com.wxb.hello.activemq.consumer;

import com.wxb.hello.activemq.repository.MessageObject;
import org.springframework.jms.support.JmsUtils;

import javax.jms.*;
import java.util.HashMap;

/**
 * describe:
 *
 * @author : 王校兵
 * @version : v1.0
 * @time : 2017/7/27  14:48
 */

public class MessageReceiver implements javax.jms.MessageListener {

    @Override
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            try {
                String text = textMessage.getText();
                System.out.println(String.format("接收到重试发送的消息: %s", text));
                throw new JMSException("process failed");
            } catch (JMSException e) {
                System.out.println("there is JMS exception: " + e.getMessage());
                throw JmsUtils.convertJmsAccessException(e);
            }
        } else if (message instanceof ObjectMessage) {

            ObjectMessage objectMessage = (ObjectMessage) message;
            try {
                MessageObject messageObject = (MessageObject) objectMessage.getObject();
                System.out.println(messageObject);
            } catch (JMSException e) {
                e.printStackTrace();
            }

        } else if (message instanceof MapMessage) {

            MapMessage mapMessage = (MapMessage) message;
            try {
                System.out.println(mapMessage.getString("a"));
                System.out.println(mapMessage.getString("b"));
                System.out.println(mapMessage.getString("c"));
            } catch (JMSException e) {
                e.printStackTrace();
            }
        } else if (message instanceof BytesMessage) {
            byte[] b = new byte[1024];
            int len = -1;
            BytesMessage bm = (BytesMessage) message;
            try {
                while ((len = bm.readBytes(b)) != -1) {
                    System.out.println(new String(b, 0, len));
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        } else if (message instanceof StreamMessage) {
            StreamMessage sm = (StreamMessage) message;
            try {
                System.out.println(sm.readString());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}
